{extend name="index:layout" /}

{block name="menu"}{/block}

{block name="content"}
<link rel="stylesheet" href="/public/static/layui/css/layui.css"  media="all">
<script src="__STATIC__/js/core/vue.js"></script>

<script type="text/javascript">
<!--
if (navigator.userAgent.indexOf("MSIE") >= 0) {
	alert("请使用谷歌或火狐访问.其它浏览器无法操作与使用");
}
//-->
</script>
<style type="text/css">
.locktr td,.locktr td a{
	color:orange;
}
.progress_warp{
	position:fixed;
	top:65%; 
	z-index:9999999999;
	width:100%;
	display:none;
}
.progress_warp .layui-progress{
	margin:0 200px;
}
</style>
<form name="formlist" method="post" action="" class="up_files">
<div class="MainContainers">
  <div class="Header"><span class="tag">在线升级</span><span class="more">&gt;&gt;</span></div>
  <div class="Conter">
<table class="ListTable" id="upgradeTR">
   <tr> 
      <th width='8%'>选中升级</th>
      <th>文件名称</th>
      <th width='17%'>升级前时间</th>
      <th width='21%'>更新时间</th>
      <th width='19%'>对比差异</th>
    </tr>

	  <tr id="contents">
		<td colspan=5 height=30 style="background:#eee;">
		  <div align="center" style="color:red;" class="upgrade_msg">正在获取云端数据信息,请稍候...</div>
		</td>
	  </tr>

	 <tr v-for="rs in listdb" :class="rs.islock?'locktr':''">
		<td class="b red">
			 <input v-if="rs.islock==1||rs.md5!=''" :data-islock="rs.islock" :data-showfile="rs.showfile" :data-md5="rs.md5" type="checkbox" name="filedb[]" :value="rs.file+','+rs.id" onclick="if($(this).is(':checked'))layer.alert('你修改过当前文件,你确认要升级覆盖现有的文件吗?')" /> 
			 <input v-else type="checkbox" name="filedb[]" :value="rs.file+','+rs.id" checked /> {{rs.i}}
		</td>
		<td class="Left listfile" :data-id="rs.id">{{rs.showfile}}</td>
		<td>
			<div align="center">{{rs.ctime}}</div>
		</td>
		<td>{{rs.time}}</td>
		<td><a :href="'{:urls('view_file')}?filename='+rs.file+'&oldfile='+rs.showfile.replace('#','%23')+'&id='+rs.id" target="_blank">对比差异</a>
		</td>
	</tr>
 
    <tr bgcolor='#FFFFFF' align="center" class="up_btn" style="display:none;"> 
      <td colspan='5'>
        <div class='submits'>
           <input type='button' onclick="CheckAll(this.form)" name='Submit' value='反选'> 
		   <input type='button' onclick="CheckAll(this.form,'no')" name='Submit' value='全不选'> 
          <input type='button' style="background:red;" onclick="sys_upgrade();" name='Submit' value='立刻升级'>          
        </div>
        </td>
  </tr> 
  </table>

  </div>
</div>
</form>

<div class="MainContainers">
  <div class="Header"><span class="tag">升级说明</span></div>
  <div class="Conter">
    <ul class="notes">
      <li>1、你可以选择哪些文件不升级,不过你最好是在程序目录,把不想升级的文件,做个标志,比如“index.htm”不想升级,就在对应的目录创建一个文件“index.htm.lock”，这样每次升级，文件就处于非选中状态，而不会升级。</li>
  <li>2、如果网络故障,一次升级不成功,可反复升级</li>
  <li>3、如果因为升级文件被替换了,请进目录/runtime/bakfile/找回来</li>
  
    </ul>
  </div>
</div>

<div class="progress_warp">
	<div class="layui-progress layui-progress-big" lay-showpercent="true" lay-filter="progressId">
	  <div class="layui-progress-bar" lay-percent="1%"></div>
	</div>
</div>
<script src="__STATIC__/layui/layui.js"></script>
<script type="text/javascript">
var element;
$(function(){
	layui.use('element', function(){
	  element = layui.element;
	})
	//element.progress('progressId', i+'%');
})
</script>

<script language=JavaScript>
var upgrade_edition = '';
var upgrade_data = {};
//检查版本更新
function check_upgrade(){
	var now_edition = "{$upgrade.md5}";
	$.post("https://x1.php168.com/appstore/upgrade/get_edition.html?typeid={$webdb.typeid}&"+Math.random(),{
		app_edition:"{:fun('upgrade@local_edition')}",
		sys_edition:now_edition,
		domin:'{:request()->domain()}',
		appkey:'{$webdb.mymd5}'
	}).success( function(res){
		if(res.code==0){
			upgrade_data = res.data;
			if(res.data.md5!=now_edition||typeof(res.data.upgrade_msg) != "undefined"){
				if(typeof(res.data.time) == "undefined"){
					return ;
				}
				upgrade_edition = res.data.md5;
				var msg = typeof(res.data.upgrade_msg) != "undefined" ? res.data.upgrade_msg : '你的系统需要升级<br>云端更新日期:'+res.data.time;
				$(".upgrade_msg").html(msg);
				layer.confirm(msg, {
					title:'升级信息',
					btn : [ '查看升级文件(不含隐藏文件)','查看升级文件(含隐藏文件)','取消' ],
					area: ['700px', '600px'],
					btn1:function(){
						down_file_list('');
					},
					btn2:function(){
						down_file_list('show_lock_hide');
					}
				});
			}else{
				$(".upgrade_msg").html('已经是最新了,无须升级');
			}
		}else{
			layer.alert(res.msg,{time:5500});
		}
	}).fail(function (res) {
		//layer.alert('网络故障,请晚点再偿试升级!!');
		//layer.closeAll();
		layer.open({title: '网络故障,请晚点再偿试升级!!',area:['90%','90%'],content: res.responseText});
	});
}
check_upgrade();


var app_ids = {};

var vues = new Vue({
	el: '#upgradeTR',
	data: {
		listdb: [],
	},
	watch:{
		listdb: function() {
			this.$nextTick(function(){	//数据渲染完毕才执行
				var time = 100;
				$("input[data-islock=0]:not(:checked)").each(function(){
					time += 200;
					var that = $(this);
					var url = "https://x1.php168.com/appstore/upgrade/check_md5.html?path="+that.attr('data-showfile')+"&md5="+that.attr('data-md5');
					setTimeout(function(){
						if(notcheck===true){
							return ;
						}
						$.get(url,function(res){
							if(res.code==0){
								that.attr('checked',true);
							}
						});
					},time);
				});
				
				var times = 500;
				$(".listfile").each(function(){
					var that = $(this);
					if(that.attr("data-id")){
						var id = that.attr("data-id");
						if(app_ids[id]==undefined){
							app_ids[id] = {};
							times += 500;
							setTimeout(function(){
								$.get("https://x1.php168.com/appstore/wxapp.show/index.html?id="+id,function(res){
									if(res.code==0){
										//app_ids[id] = res.data;
										$(".listfile[data-id="+id+"]").append("　<a href='https://x1.php168.com/appstore/content/show/id/"+id+".html' target='_blank'>"+res.data.title+"</a>");
									}
								});
							},times);
						}
					}
				});
			});
		}
	},
	methods: {
		add_data:function(array){
			$("#contents").remove();
			array.forEach((rs,i)=>{
				rs.i = i+1;
				this.listdb.push(rs);
			});			
		}
	}		  
});

//下载文件列表,核对需要哪些更新
function down_file_list(is_show){
	layer.alert('需要一点时间,请稍候,正在从云端下载升级文件列表');
	var index = layer.load(1,{shade: [0.7, '#393D49']}, {shadeClose: true}); //0代表加载的风格，支持0-2
	$.post("{:urls('check_files')}?upgrade_edition="+upgrade_edition+"&is_show="+is_show,upgrade_data).success(function(res){
		layer.closeAll();
		if(res.code==0){			
			vues.add_data(res.data);
			/*
			var str = '';
			res.data.forEach(function(rs){
				
				var ck = rs.islock?" onclick='layer.alert(\"当前文件已锁定,你确认要升级吗?\")' ":' checked ';
				var style = rs.islock?" class='locktr' ":' ';
				str +='<tr '+style+'>'+
						  '<td class="b red"> <input type="checkbox" name="filedb[]" value="'+rs.file+','+rs.id+'" '+ck+'></td>'+   
						  '<td class="Left">'+rs.showfile+'</td>'+   
						  '<td><div align="center">'+rs.ctime+'</div></td>'+
						  '<td>'+rs.time+'</td>'+
						  '<td><a href="{:urls("view_file")}?filename='+rs.file+'&id='+rs.id+'" target="_blank">查看</a></td>'+
					  '</tr>';
					  
			});
			document.getElementById('contents').outerHTML=str;
			*/
			$(".up_btn").show();
			layer.alert('需要升级的文件列表如下,你可以有选择性的升级');
		}else{
			layer.alert(res.msg,{time:5500});
		}
	}).fail(function (res) {
		layer.closeAll();
		//layer.alert('通信失败,可能你的后台权限不足'); )
		var parsedJson = $.parseJSON(res.responseText.substr(res.responseText.indexOf('{'))); //用户程序中有UTF8 +BOM文件导致的

		if( typeof(parsedJson) == 'object' && parsedJson.code==0){
			vues.add_data(parsedJson.data);
			/*
			var str = '';
			parsedJson.data.forEach(function(rs){
				var ck = rs.islock?" onclick='layer.alert(\"当前文件已锁定,你确认要升级吗?\")' ":' checked ';
				var style = rs.islock?" class='locktr' ":' ';
				str +='<tr '+style+'>'+
						  '<td class="b red"> <input type="checkbox" name="filedb[]" value="'+rs.file+','+rs.id+'"  '+ck+'></td>'+   
						  '<td class="Left">'+rs.showfile+'</td>'+   
						  '<td><div align="center">'+rs.ctime+'</div></td>'+
						  '<td>'+rs.time+'</td>'+
						  '<td><a href="{:urls("view_file")}?filename='+rs.file+'&id='+rs.id+'" target="_blank">查看</a></td>'+
					  '</tr>';
			});
			document.getElementById('contents').outerHTML=str;
			*/
			$(".up_btn").show();
			layer.alert('需要升级的文件列表如下,你可以有选择性的升级<br>特别提醒:你的系统中有错误的UTF8 +BOM 代码文件,一般情况是新装的风格导致的,请仔细排查!');
			return ;
		}else if( typeof(parsedJson) == 'object' && parsedJson.code==1){
			layer.alert(parsedJson.msg+"<br><br>特别提醒:你的系统中有错误的UTF8 +BOM 代码文件,一般情况是新装的风格导致的,请仔细排查!",{time:5500});
			return ;
		}

		layer.confirm('通信失败,你是否要新开窗口查看一下详情？'+JSON.stringify(res), {
            btn : [ '查看详情', '取消' ]
        }, function(index) {
            window.open("{:urls('check_files')}?upgrade_edition="+upgrade_edition);
        });
	});
}

//开始升级文件
function sys_upgrade(){
	$(".up_files input[type='checkbox']").each(function(i){
		if($(this).is(':checked')==true){
			ckfile_num++;
		}
	});
	
	layer.alert('正在升级文件,请耐心稍候...');
	var index = layer.load(1,{shade: [0.7, '#393D49']}, {shadeClose: true}); //0代表加载的风格，支持0-2
	$(".progress_warp").show();
	var time = 0;
	$(".up_files input[type='checkbox']").each(function(i){
		if($(this).is(':checked')==true){
			var file_name = $(this).val();
			var obj = $(this).parent().next();
			if( file_name.indexOf('/upgrade/')>0 ){				
				time += 3000;
			}else{
				time += 500;
			}
			setTimeout(function(){
				upgrade_file(file_name,obj);
			},time);
		}
	});
}

//全部升级完毕
function end_up(){
		layer.msg('全部文件升级成功');
		$.post("{:urls('sysup')}?upgrade_edition="+upgrade_edition,upgrade_data).success(function(res){
			if(res.code==0){			
				layer.alert('本次升级完毕,'+ok_num+'个文件升级成功!');
			}else{
				layer.alert('升级信息写入失败');
			}
		}).fail(function (res) {
			layer.open({title: '网络故障,请晚点再偿试升级!!',area:['90%','90%'],content: res.responseText});
		});

}

var ckfile_num = 0;	//选中的升级文件个数
var ok_num = 0;	//成功升级文件个数
//一个一个的文件升级
function upgrade_file(filename,obj){
	$.post("{:urls('sysup')}?filename="+filename,upgrade_data).success(function(res){		
		if(res.code==0){			
			//layer.msg('文件:'+filename+' 升级成功');
			var str = obj.html()+' <font color="red">升级成功</font>';
			obj.html(str);
			ok_num++;
			if(ok_num==ckfile_num){	//全部升级完毕
				layer.closeAll();
				end_up();
				$(".progress_warp").hide();
			}
			element.progress('progressId', parseInt(ok_num*100/ckfile_num)+'%');	//升级进度
		}else{
			//layer.msg('文件:'+filename+' 升级失败:'+ res.msg,{time:2500});
			var str = obj.html()+' <font color="blue">升级失败:'+res.msg+'</font>';
			obj.html(str);
		}
	}).fail(function (res) {
		//layer.alert('通信失败,可能你的后台权限不足');
		layer.open({title: '网络故障,请晚点再偿试升级!!',area:['90%','90%'],content: res.responseText});
	});
}


var notcheck = false;
function CheckAll(form,type){
	for (var i=0;i<form.elements.length;i++){
		var e = form.elements[i];
		if(type=='no'){
			notcheck = true;
			if(e.checked == true)e.checked = false;
		}else{
			e.checked == true ? e.checked = false : e.checked = true;
		}		
	}
}

</script>
{/block}
